<?php
namespace app\api\controller;
use app\api\model\OrderModel;
use app\api\model\User;
use app\common\utils\BackNotify;
use think\Controller;
use app\common\utils\Redis;
use think\Request;

// 购买商品流程
class Order extends Common
{

    // 添加购物车
    public function getAddCar(){

        $user_id=$this->checkLoginUser();

        $goods_id=input('goods_id');

        $redis =Redis::instance();

        // $redis->hset('用户id','商品id','商品数量');
        $goods_num=$redis->hget($user_id,$goods_id);

        if($goods_num){
            $goods_num++;
            $redis->hset($user_id,$goods_id,$goods_num);
        }else{
            $redis->hset($user_id, $goods_id, 1);
        }

        to_json_encode(200, 'success', true);
    }

    // 修改购物车商品数量
    public function getChangeCarSum(){

        $user_id = $this->checkLoginUser();
        $goods_id = input('goods_id');
        $sum=input('sum');

        $redis = Redis::instance();

        if($sum == 0){
            $redis->hdel($user_id,$goods_id);
        }else{
            $redis->hset($user_id,$goods_id,$sum);
        }

        to_json_encode(200, 'success', true);
    }

    // 显示购物车商品列表
    public function getShowCarList(){

        $user_id = $this->checkLoginUser();

        $redis = Redis::instance();

        $list=$redis->hgetall($user_id);

        $goodsModel = new \app\admin\model\GoodsModel();

        $carList=[];
        foreach ($list as $gid => $sum) {

            $goodsInfo=$goodsModel->getGoodsInfoById($gid, 'goods_name,goods_type,price,goods_img,describe');

            $carList[$gid]['goods_name']= $goodsInfo['goods_name'];
            $carList[$gid]['goods_type']= $goodsInfo['goods_type'];
            $carList[$gid]['price']= $goodsInfo['price'];
            $carList[$gid]['goods_img']= $goodsInfo['goods_img'];
            $carList[$gid]['describe']= $goodsInfo['describe'];
            $carList[$gid]['sum']=$sum;
        }

        to_json_encode(200,'success',$carList);
    }

    // 提交订单
    
      public function postGenerateOrder(Request $request){
     /* 参数
    user_id
    array(
        id1 => sum1,
        id2 => sum2,
    )
    address_id
    */
            $user_id = $this->checkLoginUser(true);

         // $user_id =74;
         //   $redis =Redis::instance();

            // 生成订单
          $param=$request->post();

//          $param=<<<E
//          {"orderInfo":[{"goods_id":1,"num":3},{"goods_id":2,"num":4},{"goods_id":7,"num":4}],"addressId":2,"payType":4}
//E;
//
//          $param=json_decode($param,true);

          $order_info = $param['orderInfo'];


          $address_id=$param['addressId'];

          //当 使用 默认 地址时，判断 是否 填写了 默认地址
          if($address_id == 0)
          {
              $user_info = User::getExtendInfo($user_id);
              if(empty($user_info['address']))
              {
                  to_json_encode(400, '请补全地址信息',array('status'=>false) );

              }
          }
          //默认选择货到付款
            if(!isset($param['payType']))
            {
                $payType =1;
            }else{
                $payType =$param['payType'];
            }

            $res =OrderModel::generateGoodsOrders($user_id,$order_info,$address_id,$payType);

            if($res['status']){
                // 生成订单成功
//                foreach ($order_info as $gid => $num) {
//                   // $redis->hdel($user_id,$gid);
//                }

                BackNotify::addNotifyNum(OrderModel::getNotifyParam($res['order_id']));
                to_json_encode(200, 'success',array('order_id'=>$res['order_id']));
            }else{
                to_json_encode(400, $res['msg'],array('status'=>false) );
            }
        }

    // 预约订单列表
   
    public function getOrderList(Request $request){
        $user_id = $this->checkLoginUser(true);

        $t = time();
//        $t=1609430400;
//        $t =1578827328;
        $uptime= $request->param('uptime',$t);
        $order_info_id = $request->param('order_info_id',0);
        to_json_encode(200,'success',
            OrderModel::handleOrderList(
                OrderModel::getUserOrderList($user_id,$order_info_id,$uptime)
                ,$user_id)
        );
    }





    // 取消订单
    public function getCancelOrder(){

        $user_id = $this->checkLoginUser();

        $order_id=input('order_id');


        $status= \app\api\model\OrderModel::getOrderStatusById($order_id);

       
        switch ($status) {
            case '0':
                to_json_encode(300, '参数有误，取消失败', array('status'=>false));

            case '1':
                // 未付款
                $res= \app\api\model\OrderModel::changeOrderStatusById($order_id,5);

                if($res){
                    to_json_encode(200, 'success', true);
                }else{
                    to_json_encode(400, '取消订单失败', array('status'=>false));
                }
                break;
            case '2' :
                //已付款 未发货
                $res = \app\api\model\OrderModel::changeOrderStatusById($order_id, 5);

                if ($res) {
                    // 调用支付 退回资金
                    $payback=\app\api\controller\Pay::payBack($order_id);

                    if($payback){
                        to_json_encode(200, 'success', '');
                    }
                } 
                to_json_encode(400, '取消订单失败', array('status'=>false));
                break;
	   case '6':
                // 货到付款，还未发货
                $res= \app\api\model\OrderModel::changeOrderStatusById($order_id,5);

                if($res){
                    to_json_encode(200, 'success', array('status'=>true));
                }else{
                    to_json_encode(400, '取消订单失败', array('status'=>false));
                }
                break;
            default:
                to_json_encode(400, '当前订单状态不允许取消',array('status'=>false));
                break;
        }
    }

   
    public function postDeleteOrder(Request $request){
        $user_id = $this->checkLoginUser(true);

        $order_id= $request->post('order_id');
        if(!is_numeric($order_id)){
            to_json_encode(400, '参数错误',array('status'=>false));
        }
        OrderModel::deleteOrder($user_id,$order_id);
        to_json_encode(200,'success',['status'=>true]);
    }




    // 收货地址列表
    public function getAddressList(){
        $user_id = $this->checkLoginUser();

        $list=Db('address')->field('address_id,receiver_name,receiver_phone,address,house_number')->where(['user_id'=>$user_id,'is_del'=>0])->select();

	to_json_encode(200,'success',$list);

    }


    // 添加收货地址
    public function postAddressAdd(){
        $user_id = $this->checkLoginUser();

        $param=input('post.');
        $param['user_id']=$user_id;

        if($address_id = Db('address')->insertGetId($param)){
            
            to_json_encode(200, '添加地址成功', array('address_id'=>$address_id) );
        }else{
            to_json_encode(400, '添加失败',array('status'=>false));
        }
    }
    // 删除收货地址
    public function postAddressDel()
    {
        $user_id = $this->checkLoginUser();

        $address_id = input('address_id');

        if (Db('address')->where('address_id',$address_id)->delete()) {

            to_json_encode(200, '删除成功', array('status'=>true));
        } else {
            to_json_encode(400, '操作失败', array('status'=>false));
        }
    }
    
    
}
